const express = require('express')
const multer = require('multer')
const path = require('path')
const { sendResponse } = require('../utils/sendResponse.js')

const router = express.Router()

// 设置存储位置和文件名
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, '../uploads')) // 存储在项目根目录的 'uploads' 文件夹中
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9)
    cb(null, uniqueSuffix + path.extname(file.originalname)) // 保留文件的扩展名
  }
})

// 文件过滤器，仅允许图片文件（jpg、jpeg、png、gif）
const fileFilter = (req, file, cb) => {
  const filetypes = /jpeg|jpg|png|gif/
  const mimetype = filetypes.test(file.mimetype)
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase())

  if (mimetype && extname) {
    return cb(null, true)
  } else {
    cb('Error: Images Only!')
  }
}

// 配置 multer
const upload = multer({
  storage: storage,
  limits: { fileSize: 50 * 1024 * 1024 }, // 限制文件大小为2MB
  fileFilter: fileFilter
})

// 上传图片的路由
router.post('/upload', upload.single('file'), (req, res) => {
  // 改为 'file'
  if (!req.file) {
    return sendResponse(res, 400, {}, '请上传图片文件。')
  }
  const imagePath = `/uploads/${req.file.filename}`
  return sendResponse(res, 200, { imagePath }, '图片上传成功！')
})

module.exports = router
